
	    var html='';
	    $(document).ready(function(){
	  	  $("#search_category").on("input",function(event){
	  		  searchNode(event.target.value);
	  	  });
	
	      $X("/boss/channelService", "listAllTopChannel").callx({
	        onResult: function (result) {
	            //var treeList = listToTree(result);
	            loadTreeNode(result);
	            $("#channelSelect").html(html);
	            $("#channelSelect").select2({
	                allowClear: true,
	                escapeMarkup: function (m) {
	                    return m;
	                }
	            }); 
	     		   var selectCode=$("#channelSelect").val();
	     		   //调用类目接口展示
	     		   refreshTree(selectCode);
             layer.closeAll('loading');
	        },
	        onError: function (error) {
	        	console.log(error);
	        }
	    },10000);
	    });
    	
       var treeObj;
        function refreshTree(channelCode,defNodes){
        	if(channelCode == ''){
                layer.msg("请选择渠道!");
            	  return;
              }
        	
            $X('/boss/categoryService', 'listCategoryByChannelCode').callx({
                channelCode : channelCode,
    			onResult:function(data){
   				var tree =	JSON.stringify(data);
   				tree = jQuery.parseJSON(tree);
   				//配置树的属性 
   				var setting = {
   						data:{
   							simpleData:{
   								enable:true,
   								idKey:"id",
   								pIdKey:"parentId"
   							},
   							key:{
   								name:"categoryName"
   							}
   						},
   						callback:{
   							onClick:zTreeOnclick
   						},
						view: {
							fontCss: getFontCss
						}
   					}
   				//创建自定义树
                treeObj=$.fn.zTree.init($("#treeDemo"),setting,tree);
   				if(defNodes && defNodes.length > 0 ){
   					
   					var refreshCode=defNodes[0].id;
//   					parentNode=defNodes[0].getParentNode();
//   					if(parentNode && parentNode.id) {
//   	   					//根据node id获得node节点
//   						refreshCode=parentNode.id;
//   	   		         }
   					var node = treeObj.getNodeByParam("id", refreshCode);
	   		            treeObj.selectNode(node,false);
	   		            treeObj.expandNode(node, true);
	   		         zTreeOnclick(null,null,node);
   				}
//   				$("#btn-del").hide();
//   			 	$("#btn-edit").hide();
//                $("#btn-batch").hide();
                $("button[name='uploadImgBtn']").removeClass("hidden").addClass("hidden");
                $(".revisable","#category-details").attr("disabled","disabled");
                layer.closeAll('loading');
   			}
            });
        }
           

         //点击事件 
       	function zTreeOnclick(event, treeId, treeNode){
	       	 $(".revisable","#category-details").val("");    		 
       		 $("input[name='categoryStatus']").each(function(i,obj){
       			 if(treeNode.categoryStatus == $(obj).val()){
       				 $(obj).click()
       			 }else{
       				 $(obj).removeAttr('checked');
       			 }
       		 })

            $("img[name='categoryImg']").attr('src','');
       		 
	       	 $("#id","#category-details").val(treeNode.id);
	       	 $("#nodeLevel","#category-details").val(treeNode.nodeLevel);
	         $("#categoryName","#category-details").val(treeNode.categoryName);
	         $("#categoryCode","#category-details").val(treeNode.categoryCode);
	         $("#parentIds","#category-details").val(treeNode.parentIds || '');
	         if (treeNode.categoryImgUrl){
                 $("img[name='categoryImg']").attr('src',treeNode.categoryImgUrl + '?t=' + new Date().getTime());
             }

            $("button[name='uploadImgBtn']").addClass("hidden");

	         
	         $("#commonRemark","#category-details").val(treeNode.remark);
	         $("#sortNum","#category-details").val(treeNode.sortNum);
	         
	         $(".revisable","#category-details").attr("disabled","disabled");
	         
	         $("#btn-add").hide();
             $("#btn-modify").hide();
             $("#btn-edit").show();
             $("#btn-del").show();
             $("#btn-batch").show();
       }
        
        function modify(){//查询详细信息（参数：模块id）
        	 $(".revisable","#category-details").removeAttr("disabled");
        	 $("#categoryCode","#category-details").attr("disabled","disabled");
             $("#btn-add").hide();
             $("#btn-modify").show();
            $("button[name='uploadImgBtn']").removeClass("hidden");
        }

        function addFirstCategory(){//查询详细信息（参数：模块id）
        	var channelCode =$("#channelSelect").val();
        	if(channelCode == ''){
                layer.msg("请选择渠道!");
            	  return;
              }
        	$(".revisable","#category-details").removeAttr("disabled");
       	    $(".revisable","#category-details").val("");
       	    $("input[name='categoryStatus'][value='1']").prop("checked",true); 
            $("#btn-add").show();
            $("#btn-modify").hide();
            $("#btn-del").hide();
            $("#btn-edit").hide();
            $("#btn-batch").hide();
            $("img[name='categoryImg']").attr('src','');
            $("button[name='uploadImgBtn']").removeClass("hidden");
       }
         
        function clearAll(defNodeCode){
        	
        	$(".revisable","#category-details").val("");
        	$("input[name='categoryStatus']").attr("checked",false);
            $("img[name='categoryImg']").attr('src','');
            refreshTree($("#channelSelect").val(),defNodeCode);
        }
        
      function saveAdd(){
         var channelCode = $("#channelSelect").val();
         var categoryBean = $.openx.getJsonObj('DetailsForm');
         //var categoryBean =$("#DetailsForm").serializeObject();
         categoryBean.categoryCode = $("#categoryCode").val();
         categoryBean.channelCode = channelCode;
         categoryBean.nodeLevel = 1;
         var imgUrl=$("img[name='categoryImg']").attr('src');
         if (imgUrl){
             var index=imgUrl.indexOf("?t=");
             if (index>-1){
                 imgUrl=imgUrl.substring(0,index);
             }
         }
         categoryBean.categoryImgUrl=imgUrl;
          if(channelCode == ''){
        	  layer.msg("请选择渠道!");
        	  return;
          }
          var cname = $('#categoryName').val();
          if(!cname || cname == '') {
            layer.msg("请输入类目名称!");  
            return;
          }
          var reg = new RegExp("^[0-9]*$");  
          if(!reg.test($("#sortNum").val())){  
          	layer.msg("排序请输入数字!");  
          	return;
          }  
          if(categoryBean.categoryCode == ''){
            layer.msg("请输入类目编码!");
            return;
          }
          var status = $('input[name=categoryStatus]:checked').val();
          if(!status || status == ''){
            layer.msg("请选择类目状态!");
            return;
          }
          var sNodes = treeObj.getSelectedNodes();
           $X('/boss/categoryService', 'createCategory').callx({
        	 channelCategory : categoryBean,
   			 onResult:function(data){
   				layer.msg("新增成功!");
   				clearAll(sNodes);
  			},
            //请求失败执行
            onError : function(error) {
                var res = JSON.parse(error);       
                if(res&&res.code==='70000001'&&res.message.indexOf('异常code:11030004')>-1){
                	layer.msg('该类目编码已经存在，请不用重复添加！');
                }else{
                	layer.msg(res.message)
                }
            }
           });
        }
        
        function saveModify(){
            var channelCode = $("#channelSelect").val();
            //var categoryBean = $("#DetailsForm").serializeObject();
            var categoryBean = $.openx.getJsonObj('DetailsForm');
            categoryBean.categoryCode = $("#categoryCode").val();
            categoryBean.channelCode = channelCode;
            var imgUrl=$("img[name='categoryImg']").attr('src');
            if (imgUrl) {
                var index=imgUrl.indexOf("?t=");
                if (index>-1){
                    imgUrl=imgUrl.substring(0,index);
                }
            }
            categoryBean.categoryImgUrl=imgUrl;

            if(channelCode == ''){
            layer.msg("请选择渠道!");
            return;
          }
          var cname = $('#categoryName').val();
          if(!cname || cname == '') {
            layer.msg("请输入类目名称!");  
            return;
          }
          var reg = new RegExp("^[0-9]*$");  
          if(!reg.test($("#sortNum").val())){  
            layer.msg("排序请输入数字!");  
            return;
          }  
          if(categoryBean.categoryCode == ''){
            layer.msg("请输入类目编码!");
            return;
          }
          var status = $('input[name=categoryStatus]:checked').val();
          if(!status || status == ''){
            layer.msg("请选择类目状态!");
            return;
          }
          var sNodes = treeObj.getSelectedNodes();
             $X('/boss/categoryService', 'updateCategory').callx({
            	 channelCategory : categoryBean,
     			 onResult:function(data){
     				layer.msg("修改成功!");
     				clearAll(sNodes);
       			},
                //请求失败执行
                onError : function(error) {
                    var res = JSON.parse(error);                
                    layer.msg(res.message)
                }
             });
          }
          
          function saveDel(){
        	//询问框
        	  var sNodes = treeObj.getSelectedNodes();
        	  layer.confirm('该操作将删除该类目和商品关联关系,是否继续删除该类目？', {
        	    btn: ['确认','取消'] //按钮   
        	  }, function(){
        		  id = $("#id").val();
            	  if(id == ''){
            		  layer.msg("请选择类目!");
                  	  return;
                   }
                   var categoryBean = {
                  	     id:id,
                		 delFlag:1,
                		 channelCode : $("#channelSelect").val(),
                  		 categoryCode:$("#categoryCode").val()
                	}
                  $X('/boss/categoryService', 'deleteCategory').callx({
                      id: id,
                      onResult: function (data) {
                          layer.msg("删除成功!");
                          /* $("#modal2").modal("hide"); */
                          /*clearAll(sNodes);*/
                          $(".revisable", "#category-details").val("");
                          $("input[name='categoryStatus']").attr("checked", false);
                          $("img[name='categoryImg']").attr('src', '');
                          $("#" + sNodes[0].tId).remove();
                      },
                      //请求失败执行
                      onError: function (error) {
                          var res = JSON.parse(error);
                          if (res.message.indexOf('BusinessException') > -1) {
                              layer.msg('存在子类目,无法直接删除！');
                          } else {
                              layer.msg(res.message)
                          }
                      }
                  });
        	  }, function(){
        	     
        	  });
        	
        	 
            }
          
         function modalShow(){
        	 $("#modal2").modal("show");
         }
          /*导入类目*/
          function categorysImport(){
          	var innerHtml = $.openx.innerHtml('categoryImportDiv');
          	var data = {};
          	data.id = $("#id").val();
          	data.channelCode = $("#channelSelect").val();
          	data.nodeLevel = $("#nodeLevel").val();
          	data.categoryCode=$("#categoryCode").val();
          	data.parentIds = $("#parentIds").val();
          	var categorysLayer = laytpl(innerHtml).render(data,function(html){
          		 $.openx.openLayer(['800px','400px'],'子类目导入',html,false);
          	 })
          }

        function categoryImport(){
            var innerHtml = $.openx.innerHtml('categoryImgUploadDiv');
            var data = {};
            data.channelCode = $("#channelSelect").val();
            data.categoryCode = $("#categoryCode").val();
            data.id = $("#id").val();
            var categorysLayer = laytpl(innerHtml).render(data,function(html){
                $.openx.openLayer(['800px','400px'],'图片上传',html,false);
            })
        }

        function uploadCategoryImg() {
            loadFileDataToBase64String('uploadImgId',function(img,fileType){
                if (fileType && fileType.indexOf("image")>-1){
                    $X("/boss/uploadService", "uploadImg").callx({
                    	base64Str : img,
                        channelCode : $('input[name="channelCode"]').val(),
                        categoryCode : $('input[name="categoryCode"]').val(),
                        fileType : fileType,
                        onResult : function(data) {
                            $('#uploadImgId').val('');
                            if(data){
                                data=data.replace("http://yf-base.oss-cn-shenzhen.aliyuncs.com","https://img.yifengx.com")
                                    .replace("http://yf-example.oss-cn-shenzhen.aliyuncs.com","https://yf-test-oss.yifengx.com");
                                $("img[name='categoryImg']").attr('src',data+'?t='+new Date().getTime());
                            }
                            layer.closeAll();
//                        var obj = JSON.parse(data);
//                        $("#uploadImgResult").html('导入记录成功 ：'+ obj.success  +' 条，失败记录 '+obj.error+' 条');

                        },
                        //请求失败执行
                        onError : function(error) {
                            var res = JSON.parse(error);
                            if($(".layui-layer-title").text() != ""){
                                layer.msg(res.message)
                            }
                        }
                    }, 3000*1000);
                }else{
                    layer.msg("请上传图片")
                }

            });
        }
          
          function importExcel(){	
          	loadFileDataToBase64String('importCategoryFile',function(excel,fileType){
          		$X("/boss/categoryService","importSubCategoryExcel").callx({
                base64Str:excel,
                channelCode:$("#importChannelCode").val(),
                categoryCode:$("#importCategoryCode").val(),
                onResult : function(data) {
                	$("#importExcelButton").attr("disabled", false);
                  if(data && data.length > 0) { 
                    $('#categoryResult').html(data);
                  } else {
                    $('#categoryResult').html("已加入导入队列!!!");
                  }
                },
                //请求失败执行
                onError : function(error) {
                    //layer.closeAll();
                    var res = JSON.parse(error);                
                    if($(".layui-layer-title").text() != ""){
                    	layer.msg(res.message, {
                            time: 8000
                        })
                    }
                }
              }, 3000*1000);
          	});	  	
         }
          
          function loadFileDataToBase64String(fileName, callback) {
           	var file = document.getElementById(fileName).files[0];
               if (!file) {
                   layer.msg("请选择文件");
                   return -1;
               }
               //读取文件
               var reader = new FileReader();
               reader.readAsDataURL(file);
               
               reader.onload = function () {
                   var fileType=null;
                   var prefix = this.result.split('base64,')[0];
                   if (prefix){
                       fileType=prefix.replace("data:","");
                   }
                   var result = this.result.split('base64,')[1];
                   callback(result,fileType);
               }
               
           }

          
          //渠道选择
          function listToTree(data, options) {
              options = options || {};
              var ID_KEY = options.idKey || 'id';
              var PARENT_KEY = options.parentKey || 'parentCode';
              var CHILDREN_KEY = options.childrenKey || 'children';
              var SORT=options.sort||'asc';
              var ORDERBY=options.orderBy||'id';

              var tree = [],
                  childrenOf = {};
              var item, id, parentId;

              for (var i = 0, length = data.length; i < length; i++) {
                  item = data[i];
                  id = item[ID_KEY];
                  parentId = item[PARENT_KEY] || 0;
                  // every item may have children
                  childrenOf[id] = childrenOf[id] || [];
                  // init its children
                  item[CHILDREN_KEY] = childrenOf[id];
                  if (parentId != 0) {
                      // init its parent's children object
                      childrenOf[parentId] = childrenOf[parentId] || [];
                      // push it into its parent's children object
                      childrenOf[parentId].push(item);
                  } else {
                      tree.push(item);
                  }
              };
              if(tree.length>0){
                 tree.sort(keysrt(ORDERBY,SORT.toLowerCase()==='asc'));
              }
              return tree;
          }

          function keysrt(key,asc) {
              return function(a,b){
                  return asc ? (a[key] > b[key]):(a[key] < b[key]);
              }
          }
          
          function loadTreeNode(treeNodeList) {
              if(treeNodeList && treeNodeList.length > 0){
                  for (var i = 0, length=treeNodeList.length; i<length; i++) {
                      var treeNode = treeNodeList[i];
                      var children = treeNode.children;
                      if(children&&children.length>0){  //有叶子节点的
                          html += '<optgroup label="' + treeNode.name+'">';
                          loadTreeNode(children);
                      } else {  //没有叶子节点的
                          html += '<option value="' + treeNode.channelCode + '">' + treeNode.name + '</option>';
                      }
                      if(children&&children.length>0) { 
                    	  html += '</optgroup>';
                      }
                  }
              }

          }
          var nodeList = [];
          function searchNode(value) {
              var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
//              nodeList = treeObj.getNodes()||[];
        	updateNodes(false);
        	if (value && value.trim().length>0){
                nodeList = treeObj.getNodesByParamFuzzy("categoryName",value);
                console.log(nodeList)
                if (nodeList && nodeList.length > 0) {
                    treeObj.expandAll(false);
                    treeObj.expandNode(treeObj.getNodes()[0], true, false, true);
                    updateNodes(true);
                }
            }
//  			updateNodes(true);
  		}
          
        function updateNodes(highlight) {
  			var zTree = $.fn.zTree.getZTreeObj("treeDemo");
  			if (!highlight){
                updateByParent(zTree.getNodes(), highlight);
            }else{
                for( var i=0, l=nodeList.length; i<l; i++) {
                    nodeList[i].highlight = highlight;
                    treeObj.expandNode(nodeList[i].getParentNode(), true, false, true)
                    zTree.updateNode(nodeList[i]);
                }
            }

  		}

       function updateByParent(nodeList, highlight) {
           var treeObj = $.fn.zTree.getZTreeObj("treeDemo");
           if (nodeList && nodeList.length > 0) {
               for (var i = 0, len = nodeList.length; i < len; i++) {
                   var node = nodeList[i];
                   node.highlight = highlight;
                   treeObj.updateNode(node);
                   if (node.children && node.children.length > 0) {
                       updateByParent(node.children, highlight);
                   }
               }
           }
       }

  		function getFontCss(treeId, treeNode) {
  			return (!!treeNode.highlight) ? {color:"#A60000", "font-weight":"bold"} : {color:"#333", "font-weight":"normal"};
  		}
  		 